package com.hy.utils.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//带注释的版本

@WebFilter(filterName = "a",value = "/*",initParams={@WebInitParam(name = "coding",value = "UTF-8")})
public class CodeFilter implements Filter {
    private String coding;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.coding = filterConfig.getInitParameter("coding");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response =(HttpServletResponse) servletResponse;

        if(this.coding == null)
            this.coding = "UTF-8";

        request.setCharacterEncoding(this.coding);
        response.setCharacterEncoding(this.coding);
        response.setContentType("text/html;charset="+this.coding);
        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}
